/**
 *  description：emit事件
 *  */
function broadcast (componentName, eventName, ...params) {
    this.$children.forEach(child => {
        let name = child.$options.name;
        if (name === componentName) {
            child.$emit.apply(child, [eventName].concat(params));
        } else {
            broadcast.apply(child, [componentName, eventName].concat(params));
        }
    });
}

export default {
    // 触发parent事件
    dispatch(componentName, eventName, ...params) {
        // 寻找符合要求的component
        let parent = this.$parent || this.$root;
        let name = parent.$options.name;
        while (parent && (!name || name !== componentName)) {
            parent = parent.$parent;
            if (parent) name = parent.$options.name;
        }
        // 触发符合要求组件的事件
        if (parent) parent.$emit.apply(parent, [eventName].concat(params));
    },
    // 触发children事件
    broadcast(componentName, eventName, ...params) {
        // 修改this指向，找相应的$children
        broadcast.apply(this, [eventName].concat(params));
    }
};
